变量的解构

老实讲,刚刚接触ES6时,我对变量的解构是抗拒的,因为总是很难理解,不管是数组、字符串、对象都觉得很别扭。

直到发现解构在实际开发中还是有一席之地的。

数组的解构

在ES5之前,我们声明数组一般都是这样

1
2
3
4
var arr = ['a','b','c']
console.log(arr[0]) //a
console.log(arr[1]) //b
console.log(arr[2]) //c

而有了变量解构后

1
2
3
4
let [a, b, c] = ['a', 'b', 'c'];
console.log(a) //a
console.log(b) //b
console.log(c) //c

其实对于数组来讲,有很多的解构模式,而在我看来他们的用处都一般般

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
let [foo, [[bar], baz]] = [1, [[2], 3]];
foo // 1
bar // 2
baz // 3
let [ , , third] = ["foo", "bar", "baz"];
third // "baz"
let [x, , y] = [1, 2, 3];
x // 1
y // 3
let [head, ...tail] = [1, 2, 3, 4];
head // 1
tail // [2, 3, 4]
let [x, y, ...z] = ['a'];
x // "a"
y // undefined
z // []

变量解构最大一个特点就是表达式左右必须对称,如果左右不对称就会报错

1
2
3
4
5
6
7
// 报错
let [foo] = 1;
let [foo] = false;
let [foo] = NaN;
let [foo] = undefined;
let [foo] = null;
let [foo] = {};

默认值

1
2
let [foo = true] = [];
foo // true

对象的解构

对象的解构主要用于取值

1
export { foo, bar } = { foo: "aaa", bar: "bbb" }

以及提取数据

1
2
3
4
5
6
7
8
9
10
let jsonData = {
id: 42,
status: "OK",
data: [867, 5309]
};
let { id, status, data: number } = jsonData;
console.log(id, status, number);
// 42, "OK", [867, 5309]

字符串的解构

字符串也可以解构赋值。这是因为此时,字符串被转换成了一个类似数组的对象。

1
2
3
4
5
6
const [a, b, c, d, e] = 'hello';
a // "h"
b // "e"
c // "l"
d // "l"
e // "o"

类似数组的对象都有一个length属性,因此还可以对这个属性解构赋值。

1
2
let {length : len} = 'hello';
len // 5

函数的解构

解构赋值可以方便地将一组参数与变量名对应起来。

1
2
3
4
5
6
7
// 参数是一组有次序的值
function f([x, y, z]) { ... }
f([1, 2, 3]);
// 参数是一组无次序的值
function f({x, y, z}) { ... }
f({z: 3, y: 2, x: 1});

函数只能返回一个值,如果要返回多个值,只能将它们放在数组或对象里返回。有了解构赋值,取出这些值就非常方便。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// 返回一个数组
function example() {
return [1, 2, 3];
}
let [a, b, c] = example();
// 返回一个对象
function example() {
return {
foo: 1,
bar: 2
};
}
let { foo, bar } = example();

总结

其实解构这个功能对于开发来讲还是比较有必要的,尤其用于函数和对象的解构,往往方便我们的开发。